//
//  LyOayth ViewController.swift
//  LySwift微博
//
//  Created by 贠明东 on 15/11/26.
//  Copyright © 2015年 itcCZ. All rights reserved.
//

import UIKit

import SVProgressHUD

class LyOayth_ViewController: UIViewController {

    override func loadView() {
        //不用设置约束
        view = webView
        webView.delegate = self
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //加载授权界面
        let requrst = NSURLRequest(URL: LyNetWorkTool.sharedInstance.oauthURL())
        webView.loadRequest(requrst)
        
        //设置导航栏(按钮)
        //左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
        //右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
//    填充账号
    func autoFill() {
//        创建js代码
        let js = "document.getElementById('userId').value = 'lucklyun@qq.com';                            document.getElementById('passwd').value = 'lucklyun1993';"
        
        //让webView执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
        
    }
    
    //加载AccessToken
    func loadAccessToken(code: String) {
        //发送网络请求
        LyNetWorkTool.sharedInstance.loadAccessToken(code) { (result, error) -> () in
            //判断是否有误，有误,提醒用户，关闭控制器
            //测试出错的情况(error == nil )
            if error != nil || result == nil
            {
                //告诉用户出错了
                SVProgressHUD.showErrorWithStatus("你的网络不给力…", maskType: SVProgressHUDMaskType.Gradient)

                //延时1s
                
//     OC中的GCD           dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(<#delayInSeconds#> * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//    <#code to be executed after a specified delay#>
//});
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    self.close()
                })
                return
            }
            
            //没有出错,保存数据
//            print("vc result : \(result)")
           
            // 创建模型
            let userAccount = LyUserAccount(dict: result!)
//            NSHomeDirectory()
            // 保存对象
            userAccount.saveAccout()
            
            print("userAccount:\(userAccount)")
            
        }
    }

    //关闭控制器(方法)
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //: MARK - 懒加载
    //webView
    private lazy var webView = UIWebView()
}

//MAEK：- 扩展 LyOayth_ViewController 实现 UIWebViewDelegate 协议
extension LyOayth_ViewController:UIWebViewDelegate {
    ///webView 开始加载链接
    func webViewDidStartLoad(webView: UIWebView) {
        //showWithStatus  只要没有主动关闭，就一直显示
        //showInfoWithStatus 过段时间就消失
        SVProgressHUD.showWithStatus("亡命加载ing...", maskType: SVProgressHUDMaskType.Gradient)
    }
    
    ///webView加载完成某个链接
    func webViewDidFinishLoad(webView: UIWebView) {
        //加载完就消失
        SVProgressHUD.dismiss()
    }
    //监听(webView加载链接,每当webView加载一个链接时都会询问我们这个地址是否可以加载 : true表示可以  flase表示不可以)
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        print("urlString = \(urlString)")
        
        //无论点击取消还是授权它都会跳转到我指定的网页，所以~当用户点击取消或授权，进行拦截，不让它加载，让我们来处理
        //放开(LyNetWorkTool)里的private回调地址才允许访问
        if !urlString.hasPrefix(LyNetWorkTool.sharedInstance.redirect_uri) {
             //其他情况，直接加载
            return true
        }
        //则点击了取消或授权
        //判断url地址内是否包含 code= ，截取code= 后面的字符串
        if let  query = request.URL?.query {
//            print("query = \(query)")
            let codeString = "code="
            //是否是以code=开头， 是：点击的是授权 、 否则：点击的是取消
            if query.hasPrefix(codeString)
            {
             //点击了授权,截取code的值
                let nsQuery = query as NSString
                
                //截取的长度
                let code =  nsQuery.substringFromIndex(codeString.characters.count)
                print("code = \(code)")
                
                //加载accessToken
                loadAccessToken(code)
            }else{
                //点击了取消
                print("您点击了取消")
    
                self.close()
            }
        }
        //不会去加载授权回调地址  
        return false
    }
}





